<template>
  <div class="mocks-write-main">
    <div class="write-left">
      <div class="wl-inner" v-html="articleText"></div>
    </div>
    <div class="write-right">
      <div class="wr-inner">
        <div class="wr-title">{{partInfo.describe}} ({{partInfo.score}}分)</div>
        <div class="wr-count">
          <span>Word Count : {{wordsCount}}</span>
        </div>
        <div class="wr-text">
          <textarea name="" class="wr-textarea" v-model="inputModel"></textarea>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { mapState, mapActions } from 'vuex';

  export default {
    name: "MocksWrite",
    componentType: 'paperPartQuestion',
    data () {
      return {
        inputModel: ''
      }
    },
    watch: {
      // ??
      'questionInfo' (val) {
        if(val && val.user_is_answer) {
          this.inputModel = val.user_answer;
        }
      }
    },
    computed: {
      ...mapState([
        'partInfo'
      ]),
      articleText () {
        let str = this.partInfo.content;
        return (str && typeof str === 'string') ? str.replace(/\n/g, '<br />').replace(/\t/g, '&nbsp;') : '';
      },
      questionInfo () {
        if (this.partInfo.question_list && this.partInfo.question_list.length) {
          let currentQuestion = this.partInfo.question_list[0];
          if (currentQuestion.user_is_answer) {
            this.inputModel = currentQuestion.user_answer;
          }
          return currentQuestion;
        }
        return null;
      },
      wordsCount () {
        if (this.inputModel) {
          let temp = this.inputModel.replace(/[\s+|,|.|，|。]/g, '*');
          let tempArray = temp.split('*');
          let arr= [];
          tempArray.forEach(item => {
            if (item) {
              arr.push(item)
            }
          });
          return arr.length;
        }
        return 0;
      }
    },
    methods: {
      checkUserAnswer () {
        return (!this.inputModel || !$.trim(this.inputModel))
      },
      getPartAnswer () {
        let answers = [];
        if (this.questionInfo) {
          let answer = {};
          answer.id = this.questionInfo.id;
          answer.question_type = this.questionInfo.question_type;
          answer.answer = this.inputModel;
          answers.push(answer);
        }
        return answers;
      }
    }
  }
</script>
